package org.budo.xml;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Attribute;
import org.dom4j.Branch;
import org.dom4j.Element;
import org.dom4j.Node;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Slf4j
@Getter
@Setter
@NoArgsConstructor
public class Dom4jXmlObject extends AbstractXmlObject {
    private Branch branch;

    public Dom4jXmlObject(Branch branch) {
        this.branch = branch;
    }

    @Override
    public String getNodeName() {
        if (null == this.branch) {
            return null;
        }

        return this.branch.getName();
    }

    @Override
    public String getTextContent() {
        if (null == this.branch) {
            return null;
        }

        return this.branch.getText();
    }

    @Override
    public XmlObject[] getChildNodeArray() {
        if (null == this.branch) {
            return null;
        }

        List<Node> content = this.branch.content();

        List<XmlObject> xmlObjects = new ArrayList<XmlObject>();
        for (Node node : content) {
            if (null == node || !(node instanceof Branch)) {
                log.warn("#48 this.branch=" + this.branch + ", node=" + node);
                continue;
            }

            Branch branch = (Branch) node;
            xmlObjects.add(new Dom4jXmlObject(branch));
        }

        return xmlObjects.toArray(new XmlObject[xmlObjects.size()]);
    }

    @Override
    public Map<String, String> getAttributeMap() {
        if (null == this.branch || !(this.branch instanceof Element)) {
            log.warn("#81 this.branch=" + this.branch);
            return null;
        }

        Element element = (Element) this.branch;
        List<Attribute> attributes = element.attributes();

        Map<String, String> attributeMap = new HashMap<String, String>();
        for (Attribute attribute : attributes) {
            attributeMap.put(attribute.getName(), attribute.getValue());
        }

        return attributeMap;
    }

    @Override
    public XmlObject removeChildNodeByName(String nodeName) {
        if (null == this.branch) {
            return null;
        }

        XmlObject[] childNodeArray = this.getChildNodeArrayByName(nodeName);
        for (XmlObject child : childNodeArray) {
            Dom4jXmlObject _child = (Dom4jXmlObject) child;
            this.branch.remove(_child.branch);
        }

        return this;
    }
}